import {Injectable} from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  CanActivateChild,
  Router,
  RouterStateSnapshot,
  UrlTree
} from '@angular/router';
import {Observable} from 'rxjs';
import {ElasticSearchService} from "../../service/es/elastic-search.service";

@Injectable({
  providedIn: 'root'
})
export class ConfigurationGuard implements CanActivate, CanActivateChild {


  constructor(
    private es: ElasticSearchService,
    private router: Router,
  ) {
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.handler();
  }

  canActivateChild(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.handler();
  }

  handler() {
    if (this.es.haveConfiguration()) {
      return true;
    } else {
      this.router.navigate(['/configuration'])
      return false;
    }
  }

}
